package com.sven.zuulgateway.config;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

// @Component
public class ApiFilter extends ZuulFilter {
    private static Logger logger = LoggerFactory.getLogger(ApiFilter.class);

    //filter的类型， pre、route、post、error。
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }
    //filter的执行顺序，值越小，越先执行
    @Override
    public int filterOrder() {
        return 0;
    }
    //判断请求是否需要过滤
    @Override
    public boolean shouldFilter() {
        System.out.println("---------进入ApiFilter-----shouldFilter----------");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        logger.info("receive {} request : {}", request.getMethod(), request.getRequestURL().toString());
        //含有o1需要过滤,当路径中只有部分匹配时，也要进行过滤，不区分大小写
        if (request.getRequestURI().contains("o1")) {
            return true;
        }
        return false;
    }
    //请求过滤的规则
    @Override
    public Object run() {
        System.out.println("---------进入ApiFilter-----run----------");
        //模拟异常，然后被ErrorFilter捕获
        int i=1/0;
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        //  获取传递的参数、验证权限
        String token = request.getParameter("token");
        System.out.println("token= "+ token);
        //没有携带token,不允许访问
        if (StringUtils.isEmpty(token)) {
            //告诉 Zuul 不需要将当前请求转发到后端的服务
            currentContext.setSendZuulResponse(false);
            //是用来拦截本地转发请求的，当我们配置了 forward：/local 的路由，ctx.setSendZuulResponse(false) 对 forward 是不起作用的
            // currentContext.set("sendForwardFilter.ran", true);
            //后台会接收到401未授权代码
            currentContext.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
            //这里一定要加要给Response设置CharacterEncoding编码为UTF-8
            currentContext.getResponse().setContentType("text/html;charset=UTF-8");
            currentContext.setResponseBody("{\"result\":\"请您先登陆\"}");// 返回错误内容（json格式返回）
            // currentContext.getResponse().getWriter().write("token is invalid");
            return null;
        }

        return null;
    }

}
